package io.renren.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.renren.dao.*;
import io.renren.entity.*;
import io.renren.entity.VO.EmpBaseinfoEntityVO;
import io.renren.entity.VO.EmpBaseinfoParams;
import io.renren.service.EmpBaseinfoService;
import io.renren.utils.ShiroUtils;
import io.renren.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.*;


@Service("empBaseinfoService")
public class EmpBaseinfoServiceImpl implements EmpBaseinfoService {
	@Autowired
	private EmpBaseinfoDao empBaseinfoDao;
	@Autowired
	private JobfilesDao jobfilesDao;
	@Autowired
	private CertificatesDao certificatesDao;
	@Autowired
	private EArchivesDao eArchivesDao;
	@Autowired
	private SpecialpersonDao specialpersonDao;
	@Autowired
	private PersonDispatchDao personDispatchDao;

	@Autowired
	private JobConfirmDao jobConfirmDao;

	@Autowired
	private RecruitdamandDao recruitdamandDao;
	@Autowired
	private InterviewDao interviewDao;

	@Autowired
	private EmpBlacklistDao empBlacklistDao;

	//新增页面下拉菜单名目
	private static String[] selectInfos = new String[]{"nation","polstatus","education","recruitChannel","sperson","jobfiles"};
	@Override
	public void saveEmpBaseInfo(EmpBaseinfoEntity empBaseinfo){
		empBaseinfoDao.saveEmpBaseInfo(empBaseinfo);
	}

	@Override
	public EmpBaseinfoEntity queryObject(Integer id){
		return empBaseinfoDao.queryObject(id);
	}

	@Override
	public EmpBaseinfoParams queryObjectVO(String id) {
		EmpBaseinfoParams vo = empBaseinfoDao.queryObjectVO(id);
		List<JobfilesEntity> jobfileslist = jobfilesDao.getJobfilesByEmpid(id);
		List<String> jobfiles = new ArrayList<>();
        for (JobfilesEntity jobfile : jobfileslist) {
            jobfiles.add(jobfile.getJobfile());
        }
        vo.setJobfiles(jobfiles);
        List<CertificatesEntity> certificates = certificatesDao.getCertificatesByEmpid(id);
        vo.setCertificates(certificates);
		List<EArchivesEntity> earchives = eArchivesDao.getEArchivesByEmpid(id);
		vo.setEarchives(earchives);
		List<SpecialpersonEntity> specialpersonslist = specialpersonDao.getSpecialpersonsByEmpid(id);
        List<String> specialperson = new ArrayList<>();
        for (SpecialpersonEntity specialpersonEntity : specialpersonslist) {
            specialperson.add(specialpersonEntity.getPersontype());
        }
        vo.setSpecialperson(specialperson);
        return vo;
	}

	@Override
	public List<EmpBaseinfoEntity> queryList(Map<String, Object> map){
		return empBaseinfoDao.queryList(map);
	}

	@Override
	public List<EmpBaseinfoEntityVO> queryListVO(Map<String, Object> map){
		return empBaseinfoDao.queryListVO(map);
	}


	@Override
	public Map<String, Object> getListinfo() {
		Map<String, Object> map = new HashMap<>();
		for (String selectInfo : selectInfos) {
			map.put(selectInfo,empBaseinfoDao.getSelectInfo(selectInfo));
		}
		return map;
	}
	@Override
	public int queryTotal(Map<String, Object> map){
		return empBaseinfoDao.queryTotal(map);
	}
	
	@Override
    @Transactional
	public void save(EmpBaseinfoParams empBaseinfo){
		String gw = empBaseinfo.getJob();
		EmpBaseinfoEntity baseinfo = empBaseinfoDao.getLeastRecord();
		String innerid = "00000";
		if(baseinfo!=null){
			innerid = baseinfo.getInnerid();
		}

		//生成内部编号
		String newinner = generatorSeq(innerid,gw);

        EmpBaseinfoEntity empbase = new EmpBaseinfoEntity();

		List<String> jobfiles = empBaseinfo.getJobfiles();
        List<String> sperson = empBaseinfo.getSpecialperson();

		Class empClass = empBaseinfo.getClass().getSuperclass();//获取父类Class对象
		Field[] fs = empClass.getDeclaredFields();
		for (Field f : fs) {
			f.setAccessible(true);
			String name = f.getName();// 获取属性的名字
//			name = name.substring(0, 1).toUpperCase() + name.substring(1);// 将属性的首字符大写，方便构造get，set方法
//			String type = f.getGenericType().toString();// 获取属性的类型
//			System.out.println("属性为：" + name);// 如果type是类类型，则前面包含"class "，后面跟类名
			Object val = null;
			try{
				val = f.get(empBaseinfo);//得到此属性的值
			}catch (IllegalAccessException ex){
				ex.printStackTrace();
			}

			//
			Class empb = empbase.getClass();
			Field[] fsemp = empb.getDeclaredFields();
			for(Field field : fsemp){
			    field.setAccessible(true);
			    String fname = field.getName();
			    if(!fname.equals("serialVersionUID")){
                    if(fname.equals(name)){
                        //fname = fname.substring(0, 1).toUpperCase() + fname.substring(1);
                        try {
                            field.set(empbase, val);
                            break;
                        }catch (IllegalAccessException e){
                            e.printStackTrace();
                        }
                    }
                }
            }


		}
		empbase.setInnerid(newinner);
		empBaseinfoDao.save(empbase);
		int empid = empbase.getId();
        for (String jobfile : jobfiles) {
            JobfilesEntity job = new JobfilesEntity();
            job.setEmpid(empid);
            job.setJobfile(jobfile);
            job.setStatus("0");
            jobfilesDao.save(job);
        }
        for (String s : sperson) {
            SpecialpersonEntity sp = new SpecialpersonEntity();
            sp.setEmpid(empid);
            sp.setPersontype(s);
            sp.setStatus("0");
            specialpersonDao.save(sp);
        }
        for (CertificatesEntity ce : empBaseinfo.getCertificates()) {
            ce.setEmpid(empid);
            ce.setStatus("0");
            certificatesDao.save(ce);
        }
        for (EArchivesEntity ea : empBaseinfo.getEarchives()) {
            ea.setEmpid(empid);
            ea.setStatus("0");
            eArchivesDao.save(ea);
        }

    }
	
	@Override
	public void update(EmpBaseinfoParams empBaseinfo){

		EmpBaseinfoEntity empbase = new EmpBaseinfoEntity();

		List<String> jobfiles = empBaseinfo.getJobfiles();
		List<String> sperson = empBaseinfo.getSpecialperson();

		Class empClass = empBaseinfo.getClass().getSuperclass();//获取父类Class对象
		Field[] fs = empClass.getDeclaredFields();
		for (Field f : fs) {
			f.setAccessible(true);
			String name = f.getName();// 获取属性的名字
//			name = name.substring(0, 1).toUpperCase() + name.substring(1);// 将属性的首字符大写，方便构造get，set方法
//			String type = f.getGenericType().toString();// 获取属性的类型
//			System.out.println("属性为：" + name);// 如果type是类类型，则前面包含"class "，后面跟类名
			Object val = null;
			try{
				val = f.get(empBaseinfo);//得到此属性的值
			}catch (IllegalAccessException ex){
				ex.printStackTrace();
			}

			//
			Class empb = empbase.getClass();
			Field[] fsemp = empb.getDeclaredFields();
			for(Field field : fsemp){
				field.setAccessible(true);
				String fname = field.getName();
				if(!fname.equals("serialVersionUID")){
					if(fname.equals(name)){
						//fname = fname.substring(0, 1).toUpperCase() + fname.substring(1);
						try {
							field.set(empbase, val);
							break;
						}catch (IllegalAccessException e){
							e.printStackTrace();
						}
					}
				}
			}
		}
		empBaseinfoDao.update(empbase);
		int empid = empbase.getId();
		List<JobfilesEntity>  listJobfiles=jobfilesDao.getJobfilesByEmpid(empid+"");
		if(listJobfiles!=null&&listJobfiles.size()>0){
			for(int i=0;i<listJobfiles.size();i++){
				jobfilesDao.delete(listJobfiles.get(i).getId());
			}
		}
		for (String jobfile : jobfiles) {
			JobfilesEntity job = new JobfilesEntity();
			job.setEmpid(empid);
			job.setJobfile(jobfile);
			job.setStatus("0");
			jobfilesDao.save(job);
		}
		List<SpecialpersonEntity>  listSpecialperson=specialpersonDao.getSpecialpersonsByEmpid(empid+"");
		if(listSpecialperson!=null&&listSpecialperson.size()>0){
			for(int i=0;i<listSpecialperson.size();i++){
				specialpersonDao.delete(listSpecialperson.get(i).getId());
			}
		}
		for (String s : sperson) {
			SpecialpersonEntity sp = new SpecialpersonEntity();
			sp.setEmpid(empid);
			sp.setPersontype(s);
			sp.setStatus("0");
			specialpersonDao.save(sp);
		}

		List<CertificatesEntity>  listCertificates=certificatesDao.getCertificatesByEmpid(empid+"");
		if(listCertificates!=null&&listCertificates.size()>0){
			for(int i=0;i<listCertificates.size();i++){
				certificatesDao.delete(listCertificates.get(i).getId());
			}
		}
		for (CertificatesEntity ce : empBaseinfo.getCertificates()) {
			ce.setEmpid(empid);
			ce.setStatus("0");
			certificatesDao.save(ce);
		}
		List<EArchivesEntity>  listEArchives=eArchivesDao.getEArchivesByEmpid(empid+"");
		if(listEArchives!=null&&listEArchives.size()>0){
			for(int i=0;i<listEArchives.size();i++){
				eArchivesDao.delete(listEArchives.get(i).getId());
			}
		}
		for (EArchivesEntity ea : empBaseinfo.getEarchives()) {
			ea.setEmpid(empid);
			ea.setStatus("0");
			eArchivesDao.save(ea);
		}
	}
	
	@Override
	public void delete(Integer id){
		empBaseinfoDao.delete(id);
	}

	@Override
	public void insertDispatch(JSONObject params,SysUserEntity sysUserEntity) {
		String unitId = params.get("unitId").toString();
		String dispatchType = params.get("dispatchType").toString();
		String [] ids = params.get("ids").toString().split(",");
		for(int i=0;i<ids.length;i++){
			EmpBaseinfoEntity empBaseinfoEntity = queryObject(Integer.valueOf(ids[i]));
			PersonDispatchEntity person = new PersonDispatchEntity();
			person.setSettlementId(unitId);
			person.setPersonId(empBaseinfoEntity.getId().toString());
			//person.setStation(interview.getJobid().toString());
			person.setDispatchType(dispatchType);
			person.setFileState("0");
			person.setInjury("0");
			person.setPension("0");
			person.setUnemployment("0");
			person.setMedicare("0");
			person.setMaternity("0");
			person.setAccumulationFund("0");
			person.setFiveOneInsurance("0");
			person.setOperator(sysUserEntity.getUsername());
			person.setDispatchStatus("dispatchstatus01");
			//person.setOperationDate(ca.getTime());
			person.setEnable(0);
			personDispatchDao.saveByDynamicCol(person);
			JobConfirmEntity jobConfirmEntity = new JobConfirmEntity();
			jobConfirmEntity.setAge(empBaseinfoEntity.getAge());
			//jobConfirmEntity.setCertificate(empBaseinfoEntity.getCertificate());
			jobConfirmEntity.setCompany(empBaseinfoEntity.getCompany());
			jobConfirmEntity.setCompanyid(unitId);
			//jobConfirmEntity.setDamandid(empBaseinfoEntity.getDamandid());
			jobConfirmEntity.setEducation(empBaseinfoEntity.getEducation());
			jobConfirmEntity.setEmpid(empBaseinfoEntity.getId());
			jobConfirmEntity.setEmpname(empBaseinfoEntity.getName());
			//jobConfirmEntity.setJobid(empBaseinfoEntity.getJobid());
			//jobConfirmEntity.setJobname(empBaseinfoEntity.getJobname());
			jobConfirmEntity.setMarried(empBaseinfoEntity.getMarried());
			jobConfirmEntity.setSex(empBaseinfoEntity.getSex());
			jobConfirmEntity.setStatus("0");
			//jobComfirmEntity.setBatch(date);
			jobConfirmDao.saveByDynamicCol(jobConfirmEntity);
		}

	}

	@Override
	public void insertInterview(JSONObject params, SysUserEntity sysUserEntity) {
		String demandid = params.get("demandid").toString();
		String [] baseinfoids = params.get("baseinfoids").toString().split(",");
		RecruitdamandEntity recruitdamandEntity = recruitdamandDao.queryObject(Integer.valueOf(demandid));
		for(int i=0;i<baseinfoids.length;i++){
			EmpBaseinfoEntity empBaseinfoEntity = queryObject(Integer.valueOf(baseinfoids[i]));
			InterviewEntity inter = new InterviewEntity();
			//inter.setRecruitdamandid(recruitdamandEntity.getId().toString());
			inter.setDamandid(recruitdamandEntity.getDamandid());
			inter.setAge(empBaseinfoEntity.getAge());
			inter.setEducation(empBaseinfoEntity.getEducation());
			inter.setJobid(recruitdamandEntity.getJobid());
			inter.setJobname(recruitdamandEntity.getJobname());
			inter.setMarried(empBaseinfoEntity.getMarried());
			inter.setEmpname(empBaseinfoEntity.getName());
			inter.setEmpid(empBaseinfoEntity.getId());
			//inter.setCertificate(recruitdamandEntity.getString("certificate"));
			inter.setSex(empBaseinfoEntity.getSex());
			inter.setCompany(recruitdamandEntity.getSettlementname());
			inter.setCompanyid(recruitdamandEntity.getSettlementid());
			inter.setFirInterviewStatus("0");
			interviewDao.save(inter);
			recruitdamandDao.changeFreeFlag(empBaseinfoEntity.getId());
		}
	}

	@Override
	public void deleteBatch(Integer[] ids){
		empBaseinfoDao.deleteBatch(ids);
	}

	@Override
	public void updateStatus(JSONObject params){
		String idss=  params.getString("ids") ;
		String reason=params.get("reason").toString();

		String[] ids = idss.substring(1,idss.length()-1).split(",");
		for (Object id : ids) {
			id = id.toString().substring(1,id.toString().length()-1);
			SysUserEntity user= (SysUserEntity) ShiroUtils.getSubject().getSession().getAttribute("user");
			EmpBaseinfoEntity pojo=this.queryObject(Integer.valueOf(id.toString()));
			EmpBlacklistEntity entity=new EmpBlacklistEntity();
			entity.setEmpName(pojo.getName());
			entity.setEmpNo(pojo.getId()+"");
			entity.setCardNo(pojo.getIdno());
			entity.setEmpState(pojo.getIswork());
			entity.setIfLock("0");
			entity.setLockTime(new Date());
			entity.setLockReason(reason);
			entity.setLockPerson(user.getUserdesc());
			empBlacklistDao.save(entity);
			empBaseinfoDao.updateStatusById(id);


		}
	}

	public String generatorSeq(String innerid, String gw){
		Calendar ca = Calendar.getInstance();
		int year = ca.get(Calendar.YEAR);
		String seq = null;
		if(StringUtils.isBlank(innerid)){
			seq = "00000";
		}else{
			String inyear = innerid.substring(0,4);
			if(!inyear.equals(String.valueOf(year))){
				seq = "00000";
			}else {
				seq = innerid.substring(5, 10);
			}
		}


		int es = Integer.valueOf(seq);
		es++;
		String str = String.format("%05d", es);
		/*String str = String.valueOf(es);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 5-str.length(); i++) {
			sb.append('0');
		}
		sb.append(str);*/
		return year+"-"+str+gw;
	}
}
